
(function ($, win, doc, body) {
  var
    $body = $(body);

  var FormMethods = {
    validate_form : function (evt) {
      return true;
    },

    // authority
    log_in : function (evt) {
      var
        username = null, password = null,
        $this = $(this),
        $page = $this.parents('div.ui-page:first');

      if (!FormMethods.validate_form.apply(this, [evt])) {
        return undefined;
      }

      username = $this.find('input.username-field:first').val() || username;
      password = $this.find('input.password-field:first').val() || password;

      if (username && password) {
        if (Teamlab.login(username, password)) {
          $this.addClass('processing');
        }
      }
    },

    // отправить сообщение из формы
		add_message_to_discussion : function (evt) {
      var
        fn = null,
        subject = '',
        message = '',
        discussionid = null,
        parentid = null,
        $this = $(this),
        isUpdating = false,
        $page = $this.parents('div.ui-page:first'),
        $form = $page.find('div.form-item:first'),
        $discussion = $form.parents('li.discussion-item:first'),
        $textarea = $form.find('textarea.textarea-message:first');

      isUpdating = $discussion.hasClass('editing');
      if (isUpdating) {
        discussionid = $discussion.attr('data-id') || null;
        parentid = $discussion.parents('li.discussion-item:first').attr('data-id') || null;
        subject = $discussion.find('div.title:first').text();
        fn = Teamlab.discussionsUpdateComment;
      } else {
        discussionid = $page.attr('data-itemid') || null;
        parentid = $discussion.attr('data-id') || null;
        subject = $page.find('div.user-block.discussions-item:first').find('div.title:first .inner-text:first').text();
        fn = Teamlab.discussionsAddComment;
      }
      message = $textarea.is('textarea') ? $textarea.val() : message;

      if (typeof fn === 'function' && discussionid && typeof message === 'string' && message.length > 0) {
        if (fn(discussionid, parentid, subject, message)) {
          $form.addClass('processing');
        }
      }
	  },

    // добавить задачу
    add_new_task : function (evt) {
      var
        tasktitle = null, projectid = null, responsibleid = null,
        $this = $(this);
        
      if (!FormMethods.validate_form.apply(this, [evt])) {
        return undefined;
      }

      tasktitle = $this.find('input.task-title:first').val() || tasktitle;
      projectid = $this.find('select.task-projectid:first').val() || projectid;
      responsibleid = $this.find('select.task-responsibleid:first').val() || responsibleid;

      if (tasktitle && projectid && responsibleid) {
        if (Teamlab.addTask(tasktitle, projectid, responsibleid)) {
          $this.addClass('processing');
        }
      }
    }
  };

  var LinkMethods = {
    // запретить переход
    target_none : function (evt) {
      evt.preventDefault();
    }
  };

	var ButtonMethods = {
    // скрыть форму
    close_form : function (evt) {
      $body.trigger('click');
    },

    // удалить блок
		close_user_block : function (evt) {
			$(this).parents('div.user-block:first').remove();
		},

    // переключить раздел в блоке
		user_menu_item : function (evt) {
			var
				$this = $(this),
				selectedclass = null,
				classes = ['tasks', 'projects'],
				classesInd = 0;
			classesInd = classes.length;
			while (classesInd--) {
				if ($this.hasClass(classes[classesInd])) {
					selectedclass = classes[classesInd];
					break;
				}
			}
	
			if (selectedclass) {
				var $userblock = $this.parents('div.user-block:first');
				if ($userblock.length > 0) {
					classesInd = classes.length;
					while (classesInd--) {
						$userblock.removeClass(classes[classesInd]);
					}
					$userblock.addClass(selectedclass);
				}
			}
		},

    // скрыть/показать блок
		toggle_user_block : function (evt) {
			$(this).parents('div.user-block:first').toggleClass('minimized');
		},

    // показать форму добавления задачи
		show_add_task_form : function (evt) {
		  var
			  $userblock = $(this).parents('div.user-block:first');

		  if ($userblock.hasClass('showed-addtaskform')) {
        return undefined;
      }

      $userblock.addClass('showed-addtaskform').find('div.form-container.add-new-task:first').show();
      setTimeout(function () {
        $(body).bind('click', function (evt) {
          var $target = $(evt.target);
          if ($target.is('div.form-container.add-new-task') ||  $target.parents('div.form-container.add-new-task:first').length > 0) {
						return undefined;
					}
					$(body).unbind('click', arguments.callee);
					$('div.user-block').removeClass('showed-addtaskform').find('div.form-container').hide();
        });        
      }, 1);
		},

    // открыть чат
    im_client : function (evt) {
      var
        $this = $(this),
        userid = $this.parents('div.tmusercard-container:first').attr('data-id'),
        useremail = $this.parents('div.tmusercard-container:first').attr('data-email');

      if (useremail || userid) {
        console.log(useremail || userid);
      }
    },

    // свернуть/развернуть элемент в коллекции
		toggle_collection_item : function (evt) {
			$(this).parents('li.collection-item:first').toggleClass('deployed');
	  },

    // отметить/снять отметку с элемента коллекции
    marked_coolection_item : function (evt) {
      $(this).parents('li.collection-item:first').toggleClass('marked');
    },

    // удалить элемент коллекции
    remove_collection_item : function (evt) {
      $(this).parents('li.collection-item:first').remove();
    },

    // отметить/снять отметку с дискуссии
    marked_discussion_item : function (evt) {
      $(this).parents('li.discussion-item:first').toggleClass('marked');
    },

    // удалить элемент дискуссии
    remove_discussion_item : function (evt) {
      ButtonMethods.cancel_action_to_discussion.apply(this, [evt, true]);

      var
        discussionid = 0,
        $this = $(this),
        $discussion = $this.parents('li.discussion-item:first');

      discussionid = $discussion.attr('data-id');
      if (discussionid) {
        Teamlab.discussionsRemoveComment(discussionid);
      }
      $discussion.remove();
    },

    // редактировать комментарий
    edit_discussion_item : function (evt) {
      ButtonMethods.cancel_action_to_discussion.apply(this, [evt]);

      var
        message = '',
        $this = $(this),
        $discussion = $this.parents('li.discussion-item:first'),
        $page = $this.parents('div.ui-page:first'),
        $form = $page.find('div.form-item:first'),
        $textarea = $form.find('textarea.textarea-message:first');

      message = $discussion.attr('data-encodetext');
      if (typeof message === 'string') {
        $discussion.addClass('editing').find('ul.discussion:first').before($form);
        $textarea.val(decodeURI(message)).focus();
      }
    },

    // ответить на сообщение
    reply_discussion_item : function (evt) {
      ButtonMethods.cancel_action_to_discussion.apply(this, [evt]);
      var
        $this = $(this),
        $discussion = $this.parents('li.discussion-item:first'),
        $page = $this.parents('div.ui-page:first'),
        $form = $page.find('div.form-item:first');

      $discussion.addClass('replying').find('ul.discussion:first').after($form);
      $form.find('textarea.textarea-message:first').focus();
    },

    // отменить действие
    cancel_action_to_discussion : function (evt, noneFocus) {
      var
        $page = $('div.ui-page.active:first'),
        $discussions = $page.find('ul.discussion:first'),
        $form = $page.find('div.form-item:first'),
        $textarea = $form.find('textarea.textarea-message:first');

      $discussions.find('li.discussion-item').removeClass('editing').removeClass('replying')
      $discussions.after($form);
      $textarea.val('');
      if (noneFocus !== true) {
        $textarea.focus();
      }
      evt.preventDefault();
    },

    // подгрузить задачи от проекта
    tasklists_load_tasks : function (evt) {
      var
        $this = $(this),
        projid = -1,
        $project = $this.parents('li.project::first');

      if ($project.hasClass('processing') || $project.hasClass('processed')) {
        return undefined;
      }
      projid = $project.length > 0 ? $project.attr('data-id') : projid;
      if (projid && projid > 0) {
        $project.addClass('processing');
        Teamlab.tasklistsLoadTasksByProject(projid);
      }
    },

    // подгрузить дискуссии
    discussions_load_discussions : function (evt) {
      var
        $this = $(this),
        projid = -1,
        $project = $this.parents('li.project::first');

      if ($project.hasClass('processing') || $project.hasClass('processed')) {
        return undefined;
      }
      projid = $project.length > 0 ? $project.attr('data-id') : projid;
      if (projid && projid > 0) {
        $project.addClass('processing');
        Teamlab.discussionsLoadDiscussionsByProject(projid);
      }
    }
	};

  function callMethodByClass (self, evt, container) {
    var
		  classitem = '',
		  classes = self.className.split(/\s+/),
			classesInd = 0;

		classesInd = classes ? classes.length : 0;
		while (classesInd--) {
			classitem = classes[classesInd].replace(/-/g, '_');
			if (typeof container[classitem] === 'function') {
		    container[classitem].apply(self, [evt]);
		  }
		}
  }

  function onBodyClick (evt) {
	  $(body).unbind('click', onBodyClick);
	}

  function onTextareaPress (evt) {
		switch (evt.keyCode) {
			case 13 :
			  if (evt.ctrlKey === true) {
					$(this).parents('.form-item:first').find('button.btn-submit:first').trigger('click');
				  return false;
				}
			  break;
		}
	}

  function onButtonClick (evt) {
		callMethodByClass(this, evt, ButtonMethods);
	}

  function onLinkClick (evt) {
    callMethodByClass(this, evt, LinkMethods);
  }

  function onFormSubmit (evt) {
    callMethodByClass(this, evt, FormMethods);
    return false;
  }

  function delegateEvents ($item) {
    if (!$item || $item.length === 0) {
      return undefined;
    }
    if ($item.hasClass('ui-page')) {
      // TODO
    } else if ($item.hasClass('ui-dialog')) {
      // TODO
    }

    $item.find('a').unbind('click', onLinkClick).bind('click', onLinkClick);
    $item.find('form').unbind('submit', onFormSubmit).bind('submit', onFormSubmit);
    $item.find('button').unbind('click', onButtonClick).bind('click', onButtonClick);
	  $item.find('textarea').unbind('keypress', onTextareaPress).bind('keypress', onTextareaPress);
  }

  $(window)
    .bind('render-tmusercard', function (evt, $usercard) {
      delegateEvents($usercard);
    })
    .bind('render-new-comment', function (evt, type, parentid, $comment) {
      var
        $page = $('div.ui-page.active:first'),
        $form = $page.find('div.form-item:first');

      $page.find((parentid ? 'li.comment-item[data-id="' + parentid + '"]:first ' : '') + 'ul.discussion:first').append($comment);
      $comment.find('div.item-container:first')
        .css('backgroundColor', '#FFC')
        .animate({backgroundColor : '#FFF'}, 1000);
      $form.removeClass('processing').find('textarea.textarea-message:first').val('');
      delegateEvents($comment);
    })
    .bind('render-update-comment', function (evt, type, id, $comment) {
      var
        $oldcomment = $(),
        $page = $('div.ui-page.active:first'),
        $form = $page.find('div.form-item:first');
      if (id) {
        $oldcomment = $('li.comment-item[data-id="' + id + '"]:first');
      }
      ButtonMethods.cancel_action_to_discussion.apply(this, [evt, true]);
      if ($oldcomment.length > 0) {
        $oldcomment.before($comment).remove();
      }
      $comment.find('div.item-container:first')
        .css('backgroundColor', '#FFC')
        .animate({backgroundColor : '#FFF'}, 1000);
      $form.removeClass('processing').find('textarea.textarea-message:first').val('');
      delegateEvents($comment);
    })
    .bind('render-tasklists-project-tasks', function (evt, $tasklist) {
      $('ul.collection-tasklists:first li.collection-item.project[data-id="' + 82456 + '"]:first').removeClass('processing').addClass('processed')
        .find('div.item-container:first').empty().append($tasklist);
      delegateEvents($tasklists);
    })
    .bind('render-discussions-project-discussions', function (evt, $discussions) {
      $('ul.collection-discussions:first li.collection-item.project[data-id="' + 82456 + '"]:first').removeClass('processing').addClass('processed')
        .find('div.item-container:first').empty().append($discussions);
      delegateEvents($discussions);
    })
    .bind('render-template', function (evt, $item) {
      // TODO:
    })
    .bind('change-page', function (evt) {
      $body.removeClass('rendered-page').addClass('rendering-page');
    })
    .bind('startrender-page', function (evt) {
      // TODO:
    })
    .bind('endrender-page', function (evt, $activepage, pgtype) {
      $body.removeClass('rendering-page').addClass('rendered-page');
      //setTimeout(function () {
      //  $body.removeClass('rendering-page').addClass('rendered-page');
      //}, 1000);

      var
	      userblocksIndex = 0,
	      $userblocks = $activepage.find('div.user-block'),
		    userblocksInd = $userblocks.length;
      while (userblocksInd--) {
        $($userblocks[userblocksInd]).css('zIndex', ++userblocksIndex);
	    }

      $activepage.find('a.userlink').tmuserlink();

      $activepage.find('select.combobox-gray').tmcombobox();

      $activepage.find('input.textfield-gray').tmtextfield();

      delegateEvents($activepage);

      switch (pgtype.toLowerCase()) {
        case 'page-exception' :
          break;
      }

      // TODO:
    });
})(jQuery, window, document, document.body);

